package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Article struct {
	Model
	TagID int `json:"tag_id" gorm:"index"`
	Tag Tag `json:"tag"`

	Title string `json:"title"`
	Desc string `json:"desc"`
	Content string `json:"content"`
	CreatedBy string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State int `json:"state"`
}

type ArticleList struct {
	TagID int `json:"tag_id"`
	Tag Tag `json:"tag"`

	Title string `json:"title"`
	Desc string `json:"desc"`
	Content string `json:"content"`
	State int `json:"state"`
}


func (a *Article)BeforeCreate(scope *gorm.Scope) error{
	scope.SetColumn("createdOn", time.Now().Unix())
	return nil
}

func (a *Article)BeforeUpdates(scope *gorm.Scope) error{
	scope.SetColumn("modifiedOn", time.Now().Unix())
	return nil
}
func GetArticles(pageNum int, pageSize int,maps interface{})(articles []Article) {
	//db.Model(&Article{}).Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Scan(&articles)
	db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles)
	return
}

func GetArticleTotal(maps interface {}) (count int){
	db.Model(&Article{}).Where(maps).Count(&count)

	return
}

func GetArticle(id int)(a Article) {
	db.Where("id=?", id).First(&a)
	db.Model(&a).Related(&a.Tag)
	return
}

func ExistArticleById(id int) bool {
	var a Article
	db.Where("id=?",id).First(&a)
	if a.ID > 0 {
		return true
	}
	return false
}

func AddArticle(data map[string]interface{}) bool {
	db.Create(&Article{
		TagID: data["tag_id"].(int),
		Title:data["title"].(string),
		Desc:data["desc"].(string),
		Content: data["content"].(string),
		CreatedBy: data["created_by"].(string),
		State:data["state"].(int),
	})
	return true
}
func EditArticle(id int, data interface {}) bool {
	db.Model(&Article{}).Where("id = ?", id).Updates(data)

	return true
}

func DeleteArticle(id int) bool {
	db.Where("id = ?", id).Delete(Article{})

	return true
}

func CleanAllArticle() bool {
	db.Unscoped().Where("deleted_on != ?", 0).Delete(&Article{})
	return true
}
